package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author wanghw
 * @CreateTime 2024/8/21 15:59
 * @Description 隐患分拣
 * @Version 1.0
 */
@Slf4j
@Validated
@Controller
public class hazardReportSortController extends BaseController {
    @Autowired
    private IHazardReportService hazardReportService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportSort")
    @RequiresPermissions("hazardReportSort:view")
    public String hazardReportSortIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportSort/hazardReportSortList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportSort/sort/{id}")
    @RequiresPermissions("hazardReportSort:sort")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", dto);
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportSort/hazardReportSortEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportSort/delete/{id}")
    @RequiresPermissions("hazardReportSort:delete")
    public String hazardReportDelete(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportSort/hazardReportSortDelete");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportSortRedo")
    @RequiresPermissions("hazardReportSort:redo")
    public String hazardReportSortRedoIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportSort/hazardReportSortDeletedList");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportSort/redo/{id}")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:redo")
    public FebsResponse hazardReportRedo(@PathVariable("id") String id) throws JsonProcessingException {
        HazardReport report = hazardReportService.findHazardReportById(id);
        if(ObjectUtils.isEmpty(report)){
            return new FebsResponse().fail().message("待恢复的隐患信息不存在!");
        }
        if (!HazardConstant.HAZARD_STATUS.BACK_PLAN.equals(report.getStatus())){
            return new FebsResponse().fail().message("该隐患信息已恢复！");
        }

        return new FebsResponse().success();
    }

    /**
     * 隐患分拣查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportSort/list")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        hazardReport.setStatus(HazardConstant.HAZARD_STATUS.BACK_PLAN);
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 已删除隐患列表查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportSort/deletedList")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:view")
    public FebsResponse hazardReportDeletedListList(QueryRequest request, HazardReportDto hazardReport) {
        hazardReport.setStatus(HazardConstant.HAZARD_STATUS.DELETE);
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 隐患分拣
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("整改分拣")
    @PostMapping("hazardReportSort")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:sort")
    public FebsResponse submitHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待分拣的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.BACK_PLAN.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经分拣过！");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.UPLOAD);
            this.hazardReportService.updateHazardReport(hazardReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "整改分拣失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 隐患删除
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("隐患删除")
    @PostMapping("hazardReportSort/delete")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:delete")
    public FebsResponse deletetHazardReport(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待删除的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.BACK_PLAN.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经删除，无法重复删除！");
            }
            hazardReport.setDeletedBy(getCurrentUser().getUserName());
            hazardReport.setDeletedTime(new Date());
            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.DELETE);
            this.hazardReportService.deleteHazardReportRecord(hazardReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "隐患删除失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 隐患恢复
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("隐患恢复")
    @GetMapping("hazardReportSort/repair/{id}")
    @ResponseBody
    @RequiresPermissions("hazardReportSort:delete")
    public FebsResponse repairtHazardReport(@PathVariable("id") String hazardReportId) throws FebsException {
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReportId);
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待恢复的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.DELETE.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经恢复，无法重复恢复！");
            }
            this.hazardReportService.redoHazardReportRecord(hazardReportId);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "隐患恢复失败";
            log.error(message, e);
            return failure(e,message);
        }
    }



}
